package com.milo.web.controller;

import com.milo.web.entity.PersonForm;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.validation.Valid;


/**
 * 演示springboot校验表单输入
 * @author Milo Lee
 * @date 2021-12-04 10:33
 *
 */
@Controller
public class FormValidController implements WebMvcConfigurer {
    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/results").setViewName("results");
    }

    /**
     * 浏览器访问 http://127.0.0.1:8888/web/form
     * @param personForm
     * @return
     */
    @GetMapping("form")
    public String showForm(PersonForm personForm) {
        return "form";
    }

    @PostMapping("valid")
    public String checkPersonInfo(@Valid PersonForm personForm, BindingResult bindingResult) {

        //如果存在错误,会自动回显
        if (bindingResult.hasErrors()) {
            return "form";
        }

        return "redirect:/results";
    }
}
